﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebUploaderDemo
{
    /// <summary>
    /// UploadHandler 的摘要说明
    /// </summary>
    public class UploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //context.Response.Write("Hello");
            //context.Response.End();
            if (context.Request["REQUEST_METHOD"] == "OPTIONS")
            {
                context.Response.End();
            }
            SaveFile();
        }

        private void SaveFile()
        {
            string basePath = "~/UpFolder/";
            string name;
            basePath = System.Web.HttpContext.Current.Server.MapPath(basePath);
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            if (files.Count == 0)
            {
                System.Web.HttpContext.Current.Response.Write("{\"success\" : \"0\", \"id\" : \"id\"}");
            }
            if (!System.IO.Directory.Exists(basePath))
            {
                System.IO.Directory.CreateDirectory(basePath);
            }

            var file = files[0];

            try
            {
                var suffix = files[0].ContentType.Split('/');
                //获取文件格式  
                //var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];  
                var _suffix = suffix[1];
                var _temp = System.Web.HttpContext.Current.Request["name"];
                //如果不修改文件名，则创建随机文件名  
                if (!string.IsNullOrEmpty(_temp))
                {
                    name = _temp;
                }
                else
                {
                    Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                    name = rand.Next() + "." + _suffix;
                }

                if (_suffix == "pdf")
                {
                    HttpContext.Current.Response.Write("{\"success\" : \"0\", \"id\" : \"" + name + "\"}");
                }
                else
                {
                    //文件保存  
                    var full = basePath + name;
                    //files[0].SaveAs(full);
                    System.Web.HttpContext.Current.Response.Write("{\"success\" : \"1\", \"id\" : \"" + name + "\"}");
                }
            }
            catch (Exception ex)
            {
                string err = GetString(ex.Message);
                System.Web.HttpContext.Current.Response.Write("{\"success\" : \"1\", \"id\" : \"" + file.FileName + "\", \"desc\" : \"" + err + "\"}");
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string GetString(string theString)
        {
            theString = theString.Replace(">", "&gt;");
            theString = theString.Replace("<", "&lt;");
            theString = theString.Replace(" ", "&nbsp;");
            theString = theString.Replace("\"", "&quot;");
            theString = theString.Replace("\'", "&#39;");
            theString = theString.Replace("\\", "\\\\");//对斜线的转义  
            theString = theString.Replace("\n", "\\n");  //注意php中替换的时候只能用双引号"\n"
            theString = theString.Replace("\r", "\\r");

            return theString;
        }

    }
}